package net.nohaven.proj.javeau.utils;

import java.io.ByteArrayOutputStream;

public class BitArrayOutputStream {
	private ByteArrayOutputStream baos = new ByteArrayOutputStream();

	private int[] buf = new int[8];
	private int len = 0;

	public void reset() {
		baos.reset();
		len = 0;
	}

	public void putBit(int bit) {
		buf[len++] = bit;
		if (len == 8) {
			baos.write(buf2int());
			len = 0;
		}
	}

	private byte buf2int() {
		byte ret = 0;
		for (int i = 0; i < 8; i++) {
			ret <<= 1;
			ret |= buf[i];
		}
		return ret;
	}

	private void pad() {
		putBit(1);
		while (len != 0)
			putBit(0);
	}

	public byte[] getByteArray() {
		pad();
		return baos.toByteArray();
	}
}
